package com.example.progressrecord.adpter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.progressrecord.R
import com.example.progressrecord.databinding.ItemProcessBinding
import com.example.progressrecord.decimalFormat3
import com.example.progressrecord.format
import com.example.progressrecord.formatWithTime
import com.example.progressrecord.leancloud.ProgressInfo

class ProgressInfoAdapter : RecyclerView.Adapter<ProgressInfoAdapter.ProcessViewHolder>() {

    private val progressList = mutableListOf<ProgressInfo?>()

    fun setDataList(list: List<ProgressInfo>) {
        progressList.clear()
        progressList.add(null)
        progressList.addAll(list)
    }

    fun addDataHead(info: ProgressInfo) {
        progressList.add(1, info)
        notifyItemInserted(1)
    }

    class ProcessViewHolder(val binding: ItemProcessBinding? = null, view: View? = null) :
        RecyclerView.ViewHolder(binding?.root ?: view!!)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProcessViewHolder {
        return when (viewType) {
            0 -> ProcessViewHolder(view = View(parent.context))

            else -> ProcessViewHolder(
                binding = ItemProcessBinding.inflate(
                    LayoutInflater.from(parent.context), parent, false
                )
            )
        }
    }

    override fun onBindViewHolder(holder: ProcessViewHolder, position: Int) {
        progressList[position]?.let { progress ->
            val resources = holder.itemView.context.resources
            holder.binding?.let {
                it.timeTv.text = progress.time?.formatWithTime()
                it.creatinineTv.text = resources.getString(
                    R.string.creatinine_unit, progress.creatinine.toString()
                )
                it.urine24hVolumeTv.text = resources.getString(
                    R.string.urine24h_volume_unit, progress.urine24hVolume.toString()
                )
                it.urine24hConcentrationTv.text = resources.getString(
                    R.string.urine_protein24h_concentration_unit,
                    progress.urineProtein24hConcentration.toString()
                )
                it.urine24hTv.text = resources.getString(
                    R.string.urine24h_unit,
                    progress.urineProtein24h?.decimalFormat3()
                )

                it.remarkTv.text =
                    resources.getString(R.string.remark_format,
                        progress.remark?.ifBlank {
                            it.remarkTv.visibility = View.GONE
                            ""
                        })
            }


        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == 0) 0 else 1
    }

    override fun getItemCount() = progressList.size

}